package org.binglan.youziyuepai.configuration.shiro.realm;

import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.binglan.youziyuepai.configuration.shiro.token.JwtToken;
import org.binglan.youziyuepai.entity.User;
import org.binglan.youziyuepai.exception.MyException;
import org.binglan.youziyuepai.service.UserService;
import org.binglan.youziyuepai.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;

/**
 * @description:
 * @author: sanjin
 * @date: 2019/3/20 9:26
 */
@Component
@Log4j
public class JwtRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        return null;
    }

     /**
     * 认证
     * 返回 null shiro 会抛出 UnknownAccountException 异常
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
        String jwtToken = (String) token.getCredentials();
        String userId = JwtUtils.getUsername(jwtToken);
        if (StringUtils.isBlank(userId)) {
            log.info("【JwtFilter】token错误，token=" + token);
            return null;
        }
        User queryUser = userService.queryUserById(userId);
        if (queryUser == null) {
            log.info("【JwtFilter】token 中 id 错误，id=" + userId);
            return null;
        }
        // jwt 验证 key -> id  ,  passowrd -> openid
        if (!JwtUtils.verify(jwtToken, userId, queryUser.getOpenid())) {
            log.info("【JwtFilter】openid 不正确，id=" + userId);
            return null;
        }
        return new SimpleAuthenticationInfo(jwtToken, jwtToken, getName());
    }
}
